package manager;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;

/**
 * Servlet implementation class ActivateCourse
 */
public class ActivateCourse extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
       
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		if (!request.getSession(false).getAttribute("type").equals("admin")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Admin can add courses");
			return;			
		}
		
		String name = request.getParameter("course_name");
				
		// TODO: more checking here 
		if (name == null) 
			
		{
			    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "some missing/wrong parameter");
				return;
						
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
				"SELECT 1 FROM course_sessions WHERE course_name = ?");
			
			stmnt.setString(1, name);
			ResultSet res = stmnt.executeQuery();	
			if (!res.next()) {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Course " + name + " has no sessions");
				return;
			}
			
			
			
			stmnt = dbConn.getConnection().prepareStatement(
					"UPDATE courses SET is_active = TRUE WHERE course_name = ?");
			
			stmnt.setString(1, name);
			stmnt.executeUpdate();		
			
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		response.sendRedirect("manage_courses.jsp");		
	}

}
